<template>
  <div class="user-management">
    <!-- 搜索区域 -->
    <el-card class="search-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <el-icon class="header-icon"><Search /></el-icon>
          <span class="header-title">用户搜索</span>
        </div>
      </template>
      
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            clearable
            prefix-icon="User"
            style="width: 200px;"
          />
        </el-form-item>
        
        <el-form-item label="邮箱">
          <el-input
            v-model="searchForm.email"
            placeholder="请输入邮箱"
            clearable
            prefix-icon="Message"
            style="width: 200px;"
          />
        </el-form-item>
        
        <el-form-item label="角色">
          <el-select
            v-model="searchForm.roleId"
            placeholder="请选择角色"
            clearable
            style="width: 200px;"
          >
            <el-option
              v-for="role in roleOptions"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px;"
          >
            <el-option label="启用" value="enabled" />
            <el-option label="禁用" value="disabled" />
          </el-select>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleQuery" :loading="searchLoading">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleResetQuery" :disabled="searchLoading">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 操作区域 -->
    <el-card class="main-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <el-icon class="header-icon"><User /></el-icon>
            <span class="header-title">用户管理</span>
            <el-tag v-if="total > 0" type="info" class="count-tag">
              共 {{ total }} 个用户
            </el-tag>
          </div>
          <div class="header-actions">
            <el-button type="success" @click="handleAdd" :loading="addLoading">
              <el-icon><Plus /></el-icon>
              新增用户
            </el-button>
            <el-button
              type="danger"
              @click="handleBatchDelete"
              :disabled="selectedIds.length === 0"
            >
              <el-icon><Delete /></el-icon>
              批量删除
            </el-button>
            <el-button type="info" @click="handleExport" :loading="exportLoading">
              <el-icon><Download /></el-icon>
              导出用户
            </el-button>
          </div>
        </div>
      </template>

      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        border
        v-loading="tableLoading"
        @selection-change="handleSelectionChange"
        row-key="id"
        class="user-table"
      >
        <el-table-column type="selection" width="55" />
        
        <el-table-column prop="avatar" label="头像" width="80" align="center">
          <template #default="{ row }">
            <el-avatar
              :src="row.avatar"
              :size="40"
              class="user-avatar"
            >
              {{ row.username?.charAt(0) }}
            </el-avatar>
          </template>
        </el-table-column>
        
        <el-table-column prop="username" label="用户名" width="150" show-overflow-tooltip />
        
        <el-table-column prop="mobile" label="手机号" width="130" />
        
        <el-table-column prop="email" label="邮箱" width="200" show-overflow-tooltip />
        
        <el-table-column prop="roleName" label="角色" width="120">
          <template #default="{ row }">
            <el-tag v-if="row.roleName" type="primary" size="small">
              {{ row.roleName }}
            </el-tag>
            <span v-else class="text-muted">暂无角色</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="customerName" label="所属客户" width="150" show-overflow-tooltip>
          <template #default="{ row }">
            <span v-if="row.customerName">{{ row.customerName }}</span>
            <span v-else class="text-muted">系统用户</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              active-value="enabled"
              inactive-value="disabled"
              @change="handleStatusChange(row)"
              :loading="row.statusLoading"
            />
          </template>
        </el-table-column>
        
        <el-table-column prop="lastLoginTime" label="最后登录" width="180">
          <template #default="{ row }">
            <div v-if="row.lastLoginTime" class="login-info">
              <div>{{ formatDateTime(row.lastLoginTime) }}</div>
              <div class="text-muted" style="font-size: 12px;">
                {{ row.lastLoginIp || '未知IP' }}
              </div>
            </div>
            <span v-else class="text-muted">从未登录</span>
          </template>
        </el-table-column>
        
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createdAt) }}
          </template>
        </el-table-column>
        
        <el-table-column label="操作" fixed="right" width="300">
          <template #default="{ row }">
            <el-button-group>
              <el-tooltip content="查看详情" placement="top">
                <el-button size="small" @click="handleView(row)">
                  <el-icon><View /></el-icon>
                </el-button>
              </el-tooltip>
              
              <el-tooltip content="编辑用户" placement="top">
                <el-button size="small" type="primary" @click="handleEdit(row)">
                  <el-icon><Edit /></el-icon>
                </el-button>
              </el-tooltip>
              
              <el-tooltip content="权限管理" placement="top">
                <el-button size="small" type="warning" @click="handlePermissions(row)">
                  <el-icon><Key /></el-icon>
                </el-button>
              </el-tooltip>
              
              <el-tooltip content="重置密码" placement="top">
                <el-button size="small" type="info" @click="handleResetPassword(row)">
                  <el-icon><RefreshRight /></el-icon>
                </el-button>
              </el-tooltip>
              
              <el-tooltip content="删除用户" placement="top">
                <el-button size="small" type="danger" @click="handleDelete(row)">
                  <el-icon><Delete /></el-icon>
                </el-button>
              </el-tooltip>
            </el-button-group>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          :current-page="pagination.current"
          :page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :disabled="tableLoading"
        />
      </div>
    </el-card>

    <!-- 重置密码对话框 -->
    <el-dialog v-model="passwordDialogVisible" title="重置密码" width="500px">
      <el-form ref="passwordFormRef" :model="passwordForm" :rules="passwordRules" label-width="120px">
        <el-form-item label="用户">
          <el-input v-model="passwordForm.username" disabled />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="passwordDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPasswordReset" :loading="passwordSubmitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  Search, Refresh, User, Plus, Delete, Download, View, Edit, Key, RefreshRight
} from '@element-plus/icons-vue';
import UserAPI from '@/api/system/user.api';
import { formatDateTime } from '@/utils/date';

const router = useRouter();

// 搜索表单
const searchForm = reactive({
  username: '',
  email: '',
  roleId: null,
  status: null,
});

// 表格数据
const tableData = ref([]);
const total = ref(0);
const selectedIds = ref([]);

// 角色选项
const roleOptions = ref([]);

// 加载状态
const tableLoading = ref(false);
const searchLoading = ref(false);
const addLoading = ref(false);
const exportLoading = ref(false);

// 分页
const pagination = reactive({
  current: 1,
  size: 20,
  total: 0,
});

// 密码重置
const passwordDialogVisible = ref(false);
const passwordFormRef = ref();
const passwordSubmitLoading = ref(false);
const passwordForm = reactive({
  userId: null,
  username: '',
  newPassword: '',
  confirmPassword: '',
});

const passwordRules = {
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度为6-20位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

// 角色和客户数据缓存
const roleMap = ref(new Map());
const customerMap = ref(new Map());

// 加载角色列表
const loadRoles = async () => {
  try {
    const res = await UserAPI.getRoles();
    const roles = res.data || res || [];
    roleOptions.value = roles;
    
    // 建立角色映射
    roleMap.value.clear();
    roles.forEach(role => {
      roleMap.value.set(role.id, role.name);
    });
  } catch (error) {
    console.error('加载角色列表失败:', error);
  }
};

// 加载客户列表
const loadCustomers = async () => {
  try {
    const res = await UserAPI.getCustomers();
    const customers = res.data || res || [];
    
    // 建立客户映射
    customerMap.value.clear();
    customers.forEach(customer => {
      customerMap.value.set(customer.id, customer.name);
    });
  } catch (error) {
    console.error('加载客户列表失败:', error);
  }
};

// 丰富用户数据（添加角色名称和客户名称）
const enrichUserData = async (users) => {
  if (!users || users.length === 0) return;
  
  // 确保角色和客户数据已加载
  if (roleMap.value.size === 0) {
    await loadRoles();
  }
  if (customerMap.value.size === 0) {
    await loadCustomers();
  }
  
  users.forEach(user => {
    // 添加角色名称
    if (user.roles && user.roles.length > 0) {
      // 显示第一个角色，如果有多个角色则显示角色数量
      if (user.roles.length === 1) {
        user.roleName = user.roles[0].name;
      } else {
        user.roleName = `${user.roles[0].name} 等${user.roles.length}个角色`;
      }
    } else {
      user.roleName = '暂无角色';
    }
    
    // 添加客户名称
    if (user.customerId) {
      user.customerName = customerMap.value.get(user.customerId) || '';
    }
  });
};

// 加载用户列表
const loadUsers = async () => {
  tableLoading.value = true;
  try {
    const params = {
      currentPage: pagination.current,
      pageSize: pagination.size,
      username: searchForm.username || undefined,
      email: searchForm.email || undefined,
      roleId: searchForm.roleId || undefined,
      status: searchForm.status || undefined,
    };

    const res = await UserAPI.getPage(params);
    
    if (res && res.records) {
      const users = res.records || [];
      await enrichUserData(users);
      tableData.value = users.map(user => ({
        ...user,
        statusLoading: false
      }));
      pagination.total = res.total || 0;
      total.value = res.total || 0;
    } else if (res && res.data) {
      const users = res.data.records || res.data || [];
      await enrichUserData(users);
      tableData.value = users.map(user => ({
        ...user,
        statusLoading: false
      }));
      pagination.total = res.data.total || res.total || users.length;
      total.value = res.data.total || res.total || users.length;
    } else if (res && Array.isArray(res)) {
      await enrichUserData(res);
      tableData.value = res.map(user => ({
        ...user,
        statusLoading: false
      }));
      pagination.total = res.length;
      total.value = res.length;
    }
  } catch (error) {
    ElMessage.error('加载用户列表失败: ' + (error.message || error));
    console.error('用户加载错误:', error);
    tableData.value = [];
    pagination.total = 0;
    total.value = 0;
  } finally {
    tableLoading.value = false;
  }
};

// 搜索处理
const handleQuery = async () => {
  searchLoading.value = true;
  pagination.current = 1;
  await loadUsers();
  searchLoading.value = false;
};

// 重置搜索
const handleResetQuery = () => {
  Object.assign(searchForm, {
    username: '',
    email: '',
    roleId: null,
    status: null,
  });
  pagination.current = 1;
  loadUsers();
};

// 分页处理
const handleCurrentChange = (page) => {
  pagination.current = page;
  loadUsers();
};

const handleSizeChange = (size) => {
  pagination.size = size;
  pagination.current = 1;
  loadUsers();
};

// 选择处理
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id);
};

// 状态切换
const handleStatusChange = async (row) => {
  row.statusLoading = true;
  try {
    await UserAPI.updateStatus(row.id, row.status);
    ElMessage.success(`用户已${row.status === 'enabled' ? '启用' : '禁用'}`);
  } catch (error) {
    // 状态切换失败，回滚状态
    row.status = row.status === 'enabled' ? 'disabled' : 'enabled';
    ElMessage.error('状态更新失败: ' + (error.message || error));
  } finally {
    row.statusLoading = false;
  }
};

// 新增用户
const handleAdd = async () => {
  console.log('点击新增用户按钮');
  addLoading.value = true;
  
  try {
    console.log('开始路由跳转到新增用户页面');
    await router.push({ path: '/system/user/create' });
    console.log('路由跳转成功');
  } catch (error) {
    console.error('路由跳转失败:', error);
    ElMessage.error('页面跳转失败');
  }
  
  // 重置加载状态
  addLoading.value = false;
};

// 查看详情
const handleView = (row) => {
  router.push({ path: `/system/user/detail/${row.id}` });
};

// 编辑用户
const handleEdit = (row) => {
  console.log('点击编辑用户按钮，用户ID:', row.id);
  console.log('目标路径:', `/system/user/edit/${row.id}`);
  console.log('当前路由:', router.currentRoute.value);
  
  try {
    router.push({ path: `/system/user/edit/${row.id}` });
    console.log('编辑用户路由跳转成功');
  } catch (error) {
    console.error('编辑用户路由跳转失败:', error);
    ElMessage.error('跳转失败: ' + error.message);
  }
};

// 权限管理
const handlePermissions = (row) => {
  console.log('点击权限管理按钮，用户ID:', row.id);
  console.log('目标路径:', `/system/user/permissions/${row.id}`);
  console.log('当前路由:', router.currentRoute.value);
  
  try {
    router.push({ path: `/system/user/permissions/${row.id}` });
    console.log('路由跳转成功');
  } catch (error) {
    console.error('路由跳转失败:', error);
    ElMessage.error('跳转失败: ' + error.message);
  }
};

// 重置密码
const handleResetPassword = (row) => {
  passwordForm.userId = row.id;
  passwordForm.username = row.username;
  passwordForm.newPassword = '';
  passwordForm.confirmPassword = '';
  passwordDialogVisible.value = true;
};

// 提交密码重置
const submitPasswordReset = async () => {
  if (!passwordFormRef.value) return;
  
  try {
    await passwordFormRef.value.validate();
    passwordSubmitLoading.value = true;
    
    await UserAPI.resetPassword(passwordForm.userId, passwordForm.newPassword);
    ElMessage.success('密码重置成功');
    passwordDialogVisible.value = false;
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('密码重置失败: ' + (error.message || error));
    }
  } finally {
    passwordSubmitLoading.value = false;
  }
};

// 删除用户
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除用户"${row.username}"吗？此操作不可恢复！`,
      '删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true,
      }
    );
    
    await UserAPI.deleteById(row.id);
    ElMessage.success('删除成功');
    loadUsers();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败: ' + (error.message || error));
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.value.length} 个用户吗？此操作不可恢复！`,
      '批量删除确认',
      {
        confirmButtonText: '确定删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    // 这里可以调用批量删除API
    for (const id of selectedIds.value) {
      await UserAPI.deleteById(id);
    }
    
    ElMessage.success('批量删除成功');
    selectedIds.value = [];
    loadUsers();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败: ' + (error.message || error));
    }
  }
};

// 导出用户
const handleExport = async () => {
  exportLoading.value = true;
  try {
    // 这里可以调用导出API
    ElMessage.success('导出功能开发中...');
  } catch (error) {
    ElMessage.error('导出失败: ' + (error.message || error));
  } finally {
    exportLoading.value = false;
  }
};

// 初始化
onMounted(async () => {
  // 先加载角色和客户数据，再加载用户数据
  await Promise.all([loadRoles(), loadCustomers()]);
  loadUsers();
});
</script>

<style scoped>
.user-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
}

.main-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.header-icon {
  font-size: 18px;
  color: #409eff;
}

.header-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.count-tag {
  font-size: 12px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.user-table {
  margin: 20px 0;
}

.user-avatar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  font-weight: 600;
}

.text-muted {
  color: #909399;
  font-size: 12px;
}

.login-info {
  line-height: 1.4;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
  padding: 20px 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-management {
    padding: 10px;
  }
  
  .header-actions {
    flex-direction: column;
    gap: 5px;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 10px;
  }
}

/* 动画效果 */
.el-card {
  transition: all 0.3s ease;
}

.el-card:hover {
  box-shadow: 0 2px 20px rgba(0, 0, 0, 0.1);
}

.el-button-group .el-button {
  transition: all 0.3s ease;
}

.el-table .el-table__row:hover {
  background-color: #f5f7fa;
}
</style>
